package com.xes.online.service.impl;

import com.xes.online.resources.TalSource;
import com.xes.online.service.TalSendService;
import org.apache.rocketmq.common.message.MessageConst;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.MimeTypeUtils;

import javax.annotation.Resource;

/**
 * @program: springcloud
 * @description:
 * @author: pkn
 * @create: 2020-06-28 10:10
 */
@Service
@EnableBinding(TalSource.class)
public class TalSendServiceImpl implements TalSendService {

    @Resource
    private TalSource talSource;

    @Override
    public Message send(String destination, String payload) {

        MessageChannel output = null;

        if ("output1".equals(destination)) {
            output = talSource.output1();
        } else if ("output2".equals(destination)) {
            output = talSource.output2();
        }

        Message message = MessageBuilder.withPayload(payload).build();

        output.send(message);

        return message;

    }

    @Override
    public Message sendWithTag(String destination, String payload, String tag) {
        MessageChannel output = null;

        if ("output1".equals(destination)) {
            output = talSource.output1();
        } else if ("output2".equals(destination)) {
            output = talSource.output2();
        }

        // 加单个tag
        Message message = MessageBuilder.withPayload(payload)
                .setHeader(MessageConst.PROPERTY_TAGS, tag).build();

        output.send(message);

        return message;
    }

    @Override
    public <T> Message sendObject(String destination, T msg) {
        MessageChannel output = null;

        if ("output1".equals(destination)) {
            output = talSource.output1();
        } else if ("output2".equals(destination)) {
            output = talSource.output2();
        }

        Message message = MessageBuilder.withPayload(msg)
                .setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON)
                .build();

        output.send(message);

        return message;
    }


}
